<?php
namespace Admin\Controller;

/**
 * 文章信息控制器
 */
class ArticlesController extends BaseController{
    /**
     * 文章列表
     * @return [type] [description]
     */
    public function alist(){
        $page=I('get.p')?I('get.p'):1;
        $pageSize=20;
        $where=array('a.status'=>1);
        if(I('get.title') && !empty(I('get.title'))){
            $where['a.title']=array('like','%'.trim(I('get.title')).'%');
        }
        if(I('get.start_t') && !empty(I('get.start_t'))){
            $start_t=strtotime(I('get.start_t'));
            $where['a.create_time']=array('BETWEEN',array($start_t,time()));
        }
        if(I('get.end_t') && !empty(I('get.end_t'))){
            $end_t=strtotime(I('get.end_t'))+24*3600;
            $where['a.create_time']=array('BETWEEN',array(isset($start_t)?$start_t:0,$end_t));
        }
        if(I('get.categoryID') && !empty(I('get.categoryID')) && I('get.categoryID')!=' '){
            $where['a.category_id']=I('get.categoryID');
        }
        $field='a.cover,a.banner,a.title,a.views,c.category,a.id,a.create_time,a.update_time,a.likes';
        $this->assign($this->getArtPageCate($field,$page,$where));
        $this->title='文章列表';
        $this->display();
    }

    /*
        回收站和列表共用方法，获取分类，文章数据，分页
     */
    private function getArtPageCate($field,$page,$where){
        $pageSize=20;
        $articleCount=M("articles")->alias('a')->where($where)->count();
        $Page=new \Think\Page($articleCount,$pageSize);
        $articles=M('articles')->alias('a')->field($field)
            ->join('__CATEGORIES__ c on a.category_id=c.id','LEFT')->where($where)
            ->order('a.create_time desc')->limit(($page-1)*$pageSize,$pageSize)->select();
        $Page->setConfig('header', '共<b> %TOTAL_ROW% </b>条记录，当前第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页');
        $Page->setConfig("prev","上一页");
        $Page->setConfig("next","下一页");
        $Page->setConfig('theme', '<ul class="am-pagination"><li>%UP_PAGE%</li>%LINK_PAGE%<li>%DOWN_PAGE%</li><li>%HEADER%</li></ul>');
        return array(
            'pager'=>$Page->show(),
            'articles'=>$articles,
            'categories'=>M('categories')->where('status=1')->select(),
            );
    }


    /**
     * 回收站
     * @return [type] [description]
     */
    public function recycle(){
        $page=I('get.p')?I('get.p'):1;
        $where=array('a.status'=>0);
        if(I('get.title') && !empty(I('get.title'))){
            $where['a.title']=array('like','%'.I('get.title').'%');
        }
        if(I('get.categoryID') && !empty(I('get.categoryID')) && I('get.categoryID')!=' '){
            $where['a.category_id']=I('get.categoryID');
        }
        $field='a.title,a.views,c.category,a.id,a.create_time,a.update_time,a.likes';
        $this->assign($this->getArtPageCate($field,$page,$where));
        $this->title='文章回收站';
        $this->display();
    }

    /**
     * 加入回收站
     */
    public function addRecycle(){
        if(IS_AJAX && !empty(I('post.id'))){
            if(M('articles')->save(array('id'=>I('post.id'),'status'=>0))){
                $this->ajaxReturn(array('status'=>1,'msg'=>'已加入回收站'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
            }
        }else{
            $this->error('访问错误');
        }
    }

    /**
     * 添加文章
     * @return [type] [description]
     */
    public function add(){
        if(IS_AJAX){
            $data=I('post.');
            $data1=array('content'=>$data['content']);
            unset($data['content']);
            $contentID=M('article_contents')->add($data1);
            $data['content_id']=$contentID;
            $data['create_time']=time();
            $data['update_time']=time();
            $banner=str_replace('220X144', '730X272', $data['cover']);
            if($data['is_banner']==1){
                // 首页推荐
                $data['banner']=$banner;
                if(file_exists('.'.$data['cover'])){
                    unlink('.'.$data['cover']);//删除小cover    
                }
                $data['cover']='';
            }else if($data['is_banner']==0){
                if(file_exists('.'.$banner)){
                    unlink('.'.$banner);//删除banner
                }
                if(!file_exists('.'.$data['cover'])){
                    $data['cover']='';
                }
                $data['banner']='';
            }
            if(!file_exists('.'.$banner) && $data['is_banner']==1){
                $this->ajaxReturn(array('status'=>0,'msg'=>'请重新上传封面图'));
            }
            if(M('articles')->add($data)){
                $this->ajaxReturn(array('status'=>1,'msg'=>'添加完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'添加失败'));
            }
        }
        $categories=M('categories')->where('status=1')->select();
        $this->categories=$categories;
        $this->title='添加文章';
        $this->display();
    }

    /**
     * 编辑文章
     * @return [type] [description]
     */
    public function edit(){
        if(IS_AJAX){
            $data=I('post.');
            //保存主体
            M('article_contents')->save(array('id'=>$data['acid'],'content'=>$data['content']));
            $data['update_time']=time();
            unset($data['acid']);
            unset($data['content']);
            $data['banner']=str_replace('220X144', '730X272', $data['cover']);
            $data['cover']=str_replace('730X272', '220X144', $data['cover']);
            if($data['is_banner']==1){
                // 首页置顶
                if(!file_exists('.'.$data['banner'])){
                    // 如果没有banner大图
                    $this->ajaxReturn(array('status'=>0,'msg'=>'图片不存在，请重新上传封面图'));
                }
                if(file_exists('.'.$data['cover'])){
                    unlink('.'.$data['cover']);//删除小cover    
                }
                $data['cover']='';
            }else if($data['is_banner']==0){
                //不置顶
                if(file_exists('.'.$data['banner'])){
                    unlink('.'.$data['banner']);//删除banner
                }
                if(!file_exists('.'.$data['cover'])){
                    $data['cover']='';
                }
                $data['banner']='';
            }
            $imgs=M('articles')->field('cover,banner')->find(I('post.id'));
            if(M('articles')->save($data)){
                //删除原来的图片
                if($imgs['cover']!==$data['cover'] && file_exists('.'.$imgs['cover'])){
                    unlink('.'.$imgs['cover']);
                }
                if($imgs['banner']!==$data['banner'] && file_exists('.'.$imgs['banner'])){
                    unlink('.'.$imgs['banner']);
                }
                $this->ajaxReturn(array('status'=>1,'msg'=>'修改完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'修改失败'));
            }
        }
        $categories=M('categories')->where('status=1')->select();
        $this->categories=$categories;
        $this->article=M('articles')->alias('a')->field('a.id,a.title,a.category_id,a.tags,ac.content,a.is_banner,a.banner,a.cover,ac.id as acid')
        ->join('__ARTICLE_CONTENTS__ ac ON a.content_id=ac.id','LEFT')->where('a.id='.I('get.id'))->find();
        $this->title='修改文章';
        $this->display();
    }

    /**
     * 删除文章
     * @return [type] [description]
     */
    public function deletea(){
        if(IS_AJAX){
            //原来的cover
            $oldCover=M('articles')->field('cover')->find(I('post.id'))['cover'];
            if(M('articles')->delete(I('post.id'))){
                //删除图片
                unlink('.'.$oldCover);
                $this->ajaxReturn(array('status'=>1,'msg'=>'删除完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
            }    
        }else{
            $this->error('访问错误');
        }
        
    }

    /**
     * 移出回收站
     * @return [type] [description]
     */
    public function recovery(){
        if(IS_AJAX){
            if(M('articles')->save(array('id'=>I('post.id'),'status'=>1))){
                $this->ajaxReturn(array('status'=>1,'msg'=>'恢复完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'恢复失败'));
            }    
        }else{
            $this->error('访问错误');
        }
    }
}